package kit.msc.utility;

import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

public final class Preference {

	private static Preferences prefs;
	private static String stdPrefNode = "/msc/timetable";

	public Preference() {
		init(stdPrefNode);
	}

	public static void init(String target) {
		prefs = Preferences.userRoot().node(target);

		String checkUpPrefNode = get("PrefNode", stdPrefNode);
		if (!(checkUpPrefNode.equals(stdPrefNode)))
			prefs = Preferences.userRoot().node(checkUpPrefNode);
	}

	public static String[] getPreferences() {
		try {
			return prefs.keys();
		} catch (BackingStoreException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean contains(String key) {
		try {

			for (String prefKey : prefs.keys()) {
				if (prefKey.equals(key))
					return true;
			}

		} catch (BackingStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}

	public static String get(String key, String def) {

		if (!contains(key)) {
			prefs.put(key, def);
			return def;
		} else {
			return prefs.get(key, def);
		}

	}

	public static int getInt(String string, int i) {

		if (!contains(string)) {
			prefs.putInt(string, i);
			return i;
		} else {
			return prefs.getInt(string, i);
		}

	}

	public static void remove(Object key) {
		prefs.remove((String) key);
	}

	public static void set(Object key, Object value) {
		prefs.put((String) key, (String) value);
	}

}
